package com.vini.web.panels;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.util.IOUtils;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.markup.html.link.DownloadLink;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.request.resource.ContextRelativeResource;
import org.apache.wicket.spring.injection.annot.SpringBean;

import com.vini.core.ec.Vehicle;
import com.vini.core.si.VehicleService;
import com.vini.web.AppSession;

public class VehiclePanel extends Panel {

	private static final long serialVersionUID = 1L;

	private Form<Void> vehicleForm;
	private FileUploadField upload;
	private AjaxButton uploadButton;
	private DownloadLink download;
	
	@SpringBean
	private VehicleService vehicleService;

	public VehiclePanel(String id) {
		super(id);
		 // create a feedback panel
        final FeedbackPanel feedback = new FeedbackPanel("feedback");
        feedback.setOutputMarkupPlaceholderTag(true);
        add(feedback);
        
		vehicleForm = new Form<Void>("vehicleForm"){
			private static final long serialVersionUID = 1L;

			@Override
			protected void onSubmit() {
				final FileUpload uploadedFile = upload.getFileUpload();
				if (uploadedFile != null) {
					try {
						// write to a new file
						File newFile = uploadedFile.writeToTempFile();
						uploadVehicles(newFile);
						info("Vehicles details uploaded from file: " + uploadedFile.getClientFileName());
					} catch (Exception e) {
						error("Error while saving vehicle details"+e.getMessage());
					}
				}else{
					error("Please Select a file.");
				}
			}
		};
		vehicleForm.setMultiPart(true);
		upload = new FileUploadField("fileUpload");
		uploadButton = new AjaxButton("upload") {
			private static final long serialVersionUID = 1L;
			
			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				target.add(feedback);
			}
			
			 @Override
	            protected void onError(AjaxRequestTarget target, Form<?> form){
	                target.add(feedback);
	            }

		};
		
		download = new DownloadLink("download", new AbstractReadOnlyModel<File>() {
			private static final long serialVersionUID = 1L;

			@Override
			public File getObject() {
				return getVehicleTemplateFile();
			}

		});
		
		vehicleForm.add(uploadButton);
		vehicleForm.add(download);
		vehicleForm.add(upload);
		add(vehicleForm);

	}

	protected void uploadVehicles(File newFile) {
		List<Vehicle> vehicles = new ArrayList<Vehicle>();
		Vehicle vehicle = null;
		try {
			Workbook workbook = WorkbookFactory.create(newFile);
			Sheet sheet = workbook.getSheetAt(0);
			Iterator<Row> rows = sheet.iterator();
			while (rows.hasNext()) {
				Row row = rows.next();
				if (row.getRowNum() == 0) {   //skip first row
					continue;
				}
				vehicle = new Vehicle();
				vehicle.setRegistrationNo(row.getCell(0).getStringCellValue());
				vehicle.setMake(row.getCell(1).getStringCellValue());
				vehicle.setModel(row.getCell(2).getStringCellValue());
				vehicle.setColor(row.getCell(3).getStringCellValue());
				vehicle.setCapacity((int)row.getCell(4).getNumericCellValue());
				System.out.println(vehicle.toString());
				vehicles.add(vehicle);
			}
			((AppSession)getSession()).setVehicles(vehicles);
		} catch (InvalidFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	
	private File getVehicleTemplateFile() {
		File vehicleTemplate = null;
		try{
			vehicleTemplate = File.createTempFile("vehicleTemplate", ".xlsx");
			InputStream input = new ContextRelativeResource("/template/vehicle.xlsx").getCacheableResourceStream().getInputStream();
			OutputStream output = new FileOutputStream(vehicleTemplate);
			IOUtils.copy(input, output);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return vehicleTemplate;
	}

}
